$(document).ready(function() {

    /*======update cart======*/
    $('#updCart').click(updateCart);
    
    $('#generateQuote').click(function(){
	//updating user cart first
	//updateCart();
	var quoteId = $('#quoteId-hidden').val();
	var urlwebsite = $('#wsurl-hidden').val();
	//get user mail text and internal message text
	var userMailText   = $('textarea#mailusertext').val();
	var intMessageText = $('textarea#intmsgtext').val();
	
	//show message on ajax start
	$('#ajaxmsg').ajaxStart(function(){
	    $(this).text('Generating quote. Please wait...');
	    $(this).show();
	})

	//send ajax request
	$.ajax({
	    type : 'post',
	    url : urlwebsite+'sys/backend_quote/generate/',
	    data : ({qid:quoteId, intMessage:intMessageText, usrMailText:userMailText}),
	    success: function(data){
		result = eval('(' + data + ')');
		if(result.error) {
		    $('#ajaxmsg').text(result.msg);
		}
		else {
		    $('#ajaxmsg').text('Quote generated. Mail sent to user.');
		    $('#ajaxmsg').click(function(){
			window.location.reload();
		    })
		}
	    }
	});
    });

    //changing quote status
    $('.qstatus').change(function(){
	var urlwebsite = $('#wsurl-hidden').val();
	var qId = $(this).attr('id').replace('qstat-', '');
	var newStat = $(this).val();
	$('#ajaxmsg').ajaxStart(function(){
	    $(this).text('Changing quote status. Please wait...');
	    $(this).show();
	})
	$.ajax({
	    type : 'post',
	    url : urlwebsite+'sys/backend_quote/updatestatus/',
	    data : ({qid:qId, status:newStat}),
	    success: function(data){
		result = eval('(' + data + ')');
		if(result.error) {
		    $('#ajaxmsg').text(result.msg);
		}
		else {
		    $('#ajaxmsg').text('Quote status changed');
		    //$('#ajaxmsg').click(function(){
			//window.location.reload();
		   // })
		}
	    }
	});
    });

    //removing quote
    $('.delquote').click(function(){
	if(!confirm('Do you really want to delete this quote? This operation can not be undone.')) {
	    return false;
	}
	var urlwebsite = $('#wsurl-hidden').val();
	var qId = $(this).attr('id').replace('qdel-', '');
	$('#ajaxmsg').ajaxStart(function(){
	    $(this).text('Removing quote. Please wait...');
	    $(this).show();
	})
	$.ajax({
	    type : 'post',
	    url : urlwebsite+'sys/backend_quote/deletequote/',
	    data : ({qid:qId}),
	    success: function(data){
		result = eval('(' + data + ')');
		if(result.error) {
		    $('#ajaxmsg').text(result.msg);
		}
		else {
		    window.location.reload();
		}
	    }
	});
    });

    $('#addprod').click(function(){
	var urlWebsite = $('#wsurl-hidden').val();
	Sc.init({websiteurl : urlWebsite})
	Sc.idShoppingGroups = 'sc-groups';
	Sc.idShoppingProducts = 'sc-products';
	Sc.idShoppingBrands = 'sc-brands';
	Sc.forQuote = true;
	$.ajax({
	    type : 'post',
	    url : urlWebsite+'sys/backend_container/getgroupsandbrands/',
	    success: function(data){
		result = eval('(' + data + ')');
		$('#sc-groups').html(result.groups);
		$('#sc-brands').html(result.brands);
		$('#sc-products').html(replaceOnClick(result.products));
		Sc.contentAllProducts = replaceOnClick(result.products);
	    }
	});

	//Sc.tabForContent();
	$('#sc-groupbrands').show();
    });
    
//    $('#sc-products').change(function(){
//	$(this).html(replaceOnClick($(this).html()));
//    });
})

function updateCart() {
    var urlwebsite = $('#wsurl-hidden').val();
    var cartId = $('#qid-hidden').val()
    var quoteId = $('#quoteId-hidden').val();
    //items to be removed
    var toRemove   = [];
    //items's price to be updated
    var toUpdate   = [];
    //items's note
    var adminNotes = [];
    //items's qty
    var toUpdQty   = []

    //find all remove checkboxes wich are checked and make array of items that needs to bee removed
    var remCheckboxes = $('#usercart').find('input:checkbox:checked');
    if(remCheckboxes.length) {
	$.each(remCheckboxes, function() {
	    var tmpId = $(this).attr('id');
	    toRemove.push(tmpId.replace('chkbxtorem-', ''));
	})
    }

    //make array of items that needs to be updated
    var itemsToUpdate = $('#usercart').find('.itprice');
    if(itemsToUpdate.length) {
       $.each(itemsToUpdate, function() {
	    var tmpId = $(this).attr('id');
	    toUpdate.push(tmpId.replace('inptoupd-', '') + ',' + $(this).val());
       })
    }

    //find all qtys and make an array of them
    var itemsToUpdQty = $('#usercart').find('.itqty');
    if(itemsToUpdQty.length) {
       $.each(itemsToUpdQty, function() {
	    var itemId = $(this).attr('id').replace('inptoupdcnt-', '');
	    toUpdQty.push(itemId + ',' + $(this).val());
       })
    }

    //find all notes and make an array of them
    var notes = $('#usercart').find('.adminnote');
    if(notes.length) {
       $.each(notes, function() {
	    var itemId = $(this).attr('id').replace('adminnote-', '');
	    adminNotes.push(itemId + ',' + $(this).val());
       })
    }

    //show message on ajax start
    $('#ajaxmsg').ajaxStart(function(){
	$(this).text('Updating cart. Please wait...');
	$(this).show();
    })

    //send ajax request
    $.ajax({
	type : 'post',
	url : urlwebsite+'sys/backend_quote/updatecart/',
	data : ({qid:cartId, toRemove:json_encode(toRemove), toUpdPrice:json_encode(toUpdate), toUpdQty:json_encode(toUpdQty), notes:json_encode(adminNotes)}),
	success: function(){
	    $('#ajaxmsg').hide();
	    //$('.shoppingeditquote').load(urlwebsite+'sys/backend_quote/edit/qid/' + quoteId);
	    window.location.reload();
	}
    });
}

function replaceOnClick(content) {
    return content.replace(/Sc.addVariableProductToContent\('([0-9]+)'.*\)/g, 'addProductToCart($1)');
}

function addProductToCart(id) {
    var urlwebsite = $('#wsurl-hidden').val();
    var cartId = $('#qid-hidden').val()
    $('#ajaxmsg').ajaxStart(function(){
	$(this).text('Adding product. Please wait...');
	$(this).show();
    })
    $.ajax({
	type : 'post',
	url : urlwebsite+'sys/backend_quote/addproducttocart/',
	data : ({pid:id, cid: cartId}),
	success: function(data){
	    result = eval('(' + data + ')');
	    if(result.error) {
		$('#ajaxmsg').text(result.msg);
	    }
	    else {
		window.location.reload();
	    }
	}
    });
}

function updateQuoteData(quoteId) {
    var urlwebsite = $('#wsurl-hidden').val();
    var regEmail = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})$/;

    var quoteName = $('#qupdName').val();
    var quoteMail = $('#qupdMail').val();

    if(quoteMail == '' || !quoteMail.match(regEmail) || quoteName == '') {
	alert('Please, enter a valid data.');
	return;
    }

    quoteName = quoteName.replace(/^\s+/g,'');
    quoteName = quoteName.replace(/\s+$/g,'');

    

   $('#ajaxmsg').ajaxStart(function(){
	$(this).text('Updating, please wait...');
	$(this).show();
   })
   $.ajax({
	type : 'post',
	url : urlwebsite+'sys/backend_quote/updatequoteoncreation/',
	data : ({
	    qid:quoteId,
	    qName:quoteName,
	    qMail:quoteMail,
	    country : $('#cart-quote-country').val(),
            state : $('#cart-quote-state').val(),
            city : $('#cart-quote-city').val(),
            zip : $('#cart-quote-zip').val(),
            address1 : $('#cart-quote-address1').val(),
            address2 : $('#cart-quote-address2').val(),
            phone : $('#cart-quote-phone').val(),
            comments : $('#cart-quote-comments').val()
	}),
	success: function(data){
	    result = eval('(' + data + ')');
	    if(result.error) {
		$('#ajaxmsg').text(result.msg);
	    }
	    else {
		window.location.reload();
	    }
	}
    });
}